<?php
namespace app\wechat\controller;

use app\common\base\BasicRest;
use think\Config;
use think\Db;
use think\Request;
use think\Session;

class token extends  BasicRest
{


    protected $beforeActionList = [
          'validatecsrf'
      ];

    public function __construct()
    {
        parent::__construct();
    }

    protected function validatecsrf(){
        // $csrf=$this->request->post('_CSRF');
        // if($csrf&&strlen($csrf)==12){
        //     $onedata=substr($csrf,0,4);
        //     $twodata=substr($csrf,4,4);
        //     $threedata=substr($csrf,8,4);
        //     $result= substr((string)((int)$onedata*(int)$threedata),0,4);
        //     if($result!=$twodata){
        //         echo '非法请求';
        //         exit(0);
        //     }
        // }else{
        //     echo '非法请求';
        //         exit(0);
        // }
         
    }
        
    public function verify()
    {

        try{
                $token='asdohj123ojvcxiudsf234czxf3';
            // $data = $this->request->get();
            // $echostr = Request::instance()->get('echostr');
            // input(echostr);
            Db::table('content')->insert(['content'=>json_encode($_GET),'content2'=>$_GET['echostr']]);
            // var_dump($data);
            // $echoStr = $data['echostr'];
            // $signature = $data["signature"];
            // $timestamp = $data["timestamp"];
            // $nonce = $data["nonce"];


            // $tmpArr = array($token, $timestamp, $nonce);
            // // use SORT_STRING rule
            // sort($tmpArr, SORT_STRING);
            // $tmpStr = implode($tmpArr);
            // $tmpStr = sha1($tmpStr); header('content-type:text');
            // echo $token;
            ob_clean();

            echo $_GET['echostr'];
        }catch(\Exception $e){
            Db::table('content')->insert(['content'=>$e->getMessage()]);
        }
        
        exit;
        if ($tmpStr == $signature && isset($echoStr)) {
            echo $echoStr;
            die;
        } else {
            return false;
        }
    }

    public function login(){
            $data=$this->request->post();
              if(!empty($data['code'])){

                    $secret=Config::get('wechatAppSecret');
                    $appid=Config::get('wechatAppappid');
                    $code=$data['code'];
                    $wecharurl="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=".$code."&grant_type=authorization_code";
                    $ch = curl_init(); 
                    curl_setopt($ch, CURLOPT_URL, $wecharurl); 
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                      //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60); 
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
                    $output = json_decode(curl_exec($ch),true); 
                    curl_close($ch); 
         
                    $user =UserInfoModel::get(['openid'=>$output['openid']]);
                    $loginid=md5($output['openid'].time());
                    if(!$user){
                        $user= new UserInfoModel();
                        $data['loginid']=$loginid;
                        $data['login_time']=time();
                        $data['openid']=$output['openid'];
                        $data['unionid']=$output['openid'];

                        unset($data['code']);
                        foreach($data['userInfo'] as $v=>$single){
                            $data[$v]=$single;
                        }
                        $user->data($data);
                        
                    }else{
                        $user->loginid=$loginid;
                        $user->update_time=time();
                        $data['login_time']=time();
                        $user->nickName=$data['userInfo']['nickName'];
                        $user->avatarUrl=$data['userInfo']['avatarUrl'];
                    }

                    
                    $res=$user->save();
                    if($res)return res_success(['userid'=>$loginid,'nickName'=>$user->nickName,'avatarUrl'=>$user->avatarUrl]);
                    return res_fail('登陆失败');
                    
            }else{
                return '错误的参数';
            }   
    }

    //用户扫描小程序码之后
    public function getquestion(){
        $data = $this->request->post();
        if(!$data['user_id']||!$data['active_id']){
            exit(0);
        }
        //先根据active_id的活动时间来动态的获取数据库的年份
        $active=ActiveModel::get($data['active_id']);
        if(!$active){
            return res_fail('活动失效');
            exit(0);
        }

        $table='duijiang_'.substr($active->active_time,0,4);
        $duijiang=Db::table($table)->alias('d');
        $duijiang->join('userInfo u','d.user_id=u.id','INNER');
        $duijiang->where(['u.loginid'=>$data['user_id'],'d.active_id'=>$data['active_id'],'isdeleted'=>0]);
        $duijiang->field('d.isduihuan isduihuan,d.jiangpin jiangpin,d.code code');
        $duijiangdata=$duijiang->limit(1)->find();

        //如果没有参加过活动
        if(!$duijiangdata){
            //判断活动的type
            if($active->type==1){
            
                return res_success(['status'=>1,'people_num'=>$active->people_num,'goods'=>$active->product,'q1'=>$active->question1,'q2'=>$active->question2]);
            }elseif($active->type==2){
                    //判断人数有没有到
                    $people_num=json_decode($active->people_num,true);
                    $product=json_decode($active->product,true);
                    if($product[(int)$data['goods_id']]['num']>=$people_num[(int)$data['goods_id']]){
                        return res_fail('此奖品已经兑换完');
                    }else{
                        return res_success(['status'=>1,'q1'=>$active->question1,'q2'=>$active->question2]);
                    }
                    
            }
            
        }else{
            //如果有参加活动，先获取到选的什么奖品
            $product=json_decode($active->product,true);
            $jiangpin=$product[(int)$duijiangdata->jiangpin];
            //判断有没有兑换多
            switch($duijiangdata->isduihuan){
                //没有核销
                case 0:
                    return res_success(['title'=>$jiangpin['title'],'src'=>$jiangpin['src'],'code'=>$duijiangdata->code]);
                //已经核销了
                case 1;
                     return res_success(['title'=>$jiangpin['title'],'src'=>$jiangpin['src']]);
            }
        }
    }

    //用户提交问题
    public function submitquestion(){
            $data=$this->request->post();
            $active=ActiveModel::get($data['active_id']);
            $table='duijiang_'.substr($active->active_time,0,4);
            $user=UserInfoModel::get(['loginid'=>$data['user_id']]);
            if(!$user)return res_fail('未找到用户');
            //先判断存在不存在
            $duijiang=Db::table($table)->where(['active_id'=>$data['active_id'],'user_id'=>$user->id,'isdeleted'=>0])->field('id')->limit(1)->find();
            if(!$duijiang){
                $code=md5($data['user_id'].time());
                $insertid=Db::table($table)->insert(['active_id'=>$data['active_id'],'user_id'=>$user->id,'question1'=>$data['q1'],'question2'=>$data['q2'],'code'=>$code,'jiangpin'=>$data['goods_id']]);
                if($insertid){
                    //数量添加  
                    $people_num=json_decode($active->people_num,true);
                    $active->people_num = json_encode($people_num[(int)$data['goods_id']]+1);
                    $active->save();
                    $product=json_decode($active->product,true);
                    $product=$product[(int)$data['goods_id']];
                    return res_success(['title'=>$product['title'],'src'=>$product['src'],'code'=>$code]);

                }
                return res_fail('提交失败');
            }else{
                return res_fail('已参加过活动了');
            }
    }

    //管理员获取用户提交的问题
    public function getactive(){
            $data=$this->request->post();
            $active=ActiveModel::get($data['active_id']);
            $table='duijiang_'.substr($active->active_time,0,4);
            $duijiang=Db::table($table)->where(['code'=>$data['code']])->limit(1)->find();
            if($duijiang['isduihuan']==1){
                //已经被驳回
                return res_fail('已经领取过奖品了');
            }elseif($duijiang['isdeleted']==1){
                //已经被驳回
                return res_fail('此问卷调查已被驳回');
            }elseif($duijiang['isdeleted']==0){
                $product=json_decode($active->product,true);
                $product=$product[(int)$duijiang['jiangpin']];
                return res_success(['title'=>$product['title'],'src'=>$product['src'],'q1'=>$duijiang['question1'],'q2'=>$duijiang['question2']]);
            }
    }

    //管理员确认还是驳回
    public function checkactive(){
        $data=$this->request->post();
        $active=ActiveModel::get($data['active_id']);
        $table='duijiang_'.substr($active->active_time,0,4);
        if($data['pass']==1){
            $result=Db::table($table)->where(['code'=>$data['code'],'active_id'=>$data['active_id']])->update(['isduihuan'=>1]);
            if($result) return res_success('兑换成功');
            return res_fail('兑换失败');
        }elseif($data['pass']==2){
            $result=Db::table($table)->where(['code'=>$data['code'],'active_id'=>$data['active_id']])->update(['isdeleted'=>1]);
            if($result) return res_success('驳回成功');
            return res_fail('驳回失败');
        }
        return res_fail('操作失败');
    }


    //判读用户是否登陆
    public function checkLogin(){
        $loginData = Session::get('userid');
        $loginData = '123';
        $res = UserInfoModel::get(['user_id'=>$loginData]);
        if($res) return res_success($res);
        return res_fail('未找到信息');
    }


    //获取中奖概率
    public function getChance(){
        $res = ChanceModel::all();
        if($res) return res_success($res);
        return res_fail('未找到信息');
    }

    public function getPrize(Request $request){
        $loginData = Session::get('userid');
        $loginData = '123';
        UserInfoModel::where(['user_id' => $loginData])->update(['is_draw' => 1]);
        $data = UserInfoModel::get(['user_id'=>$loginData]);
        $item = $request->post('item');
        switch ($item){
            case 1:
                $str = '未中奖';
                break;
            case 2:
                $str = '一等奖';
                break;
            case 3:
                $str = '二等奖';
                break;
            case 4:
                $str = '三等奖';
                break;
        }
        $res = RecordModel::create(["uid"=>$data->id,"reward"=>$str]);
        if($res) return res_success($res);
        return res_fail('更新失败');
    }

}